package com.kc.zhaojiu.filter;

import com.alibaba.fastjson2.JSON;
import com.kc.zhaojiu.util.CheckParams;
import com.kc.zhaojiu.util.JsonResult;
import com.kc.zhaojiu.util.JwtUtil;
import org.apache.http.HttpStatus;
import org.springframework.http.HttpMethod;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Author: QiongKe~
 * Date: 2022/10/23 16:52
 */
public class zhaojiuHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            return true;
        }
        String token = request.getHeader("token");
        System.out.println(token);
        if (!CheckParams.check(token)){
            try {
                JwtUtil.parseToken(token);     /*不用查数据库！*/  //解析令牌，如果不合法
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                //解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
                return returnResponse(response, "🐖🐖🐖🐖🐖🐖🐖🐖不合法🐖🐖🐖🐖🐖🐖");
            }
        }else {
            //响应中放入返回的状态吗, 没有权限访问
            return returnResponse(response, "🐕🐕🐕🐕🐕🐕🐕🐕缺少令牌🐕🐕🐕🐕🐕🐕🐕🐕🐕🐕");
        }
    }

    private boolean returnResponse(HttpServletResponse response, String msgTip) throws IOException {
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        //在获取流对象之前告诉浏览器使用什么字符集
        response.setCharacterEncoding("utf-8");

        //告诉浏览器，服务器发送的消息体的数据的编码
        response.setHeader("content-type","text/html;charset=utf-8");

        JsonResult<String> res = new JsonResult<>();
        res.setCode(401401401);
        res.setMessage("登录失败");
        res.setData(msgTip);
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(res));
        return false;
    }


}
